#include "propertiesdialog.h"
#include "ui_propertiesdialog.h"
#include <QDebug>
#include <QMessageBox>
#include "drawobj.h"

PropertiesDialog::PropertiesDialog(GraphicsRectItem* i, QWidget *parent) :
    QDialog(parent), m_item(i),
    ui(new Ui::PropertiesDialog)
{
    ui->setupUi(this);
    initTable();
    connect(ui->createButton,&QPushButton::clicked, this,&PropertiesDialog::onCreateBtnclicked);
    connect(ui->delButton,&QPushButton::clicked, this,&PropertiesDialog::onDelBtnclicked);
    connect(ui->confirmButton,&QPushButton::clicked, this,&PropertiesDialog::onConfirmBtnclicked);
    connect(ui->cancelButton,&QPushButton::clicked, this,&PropertiesDialog::onCancelBtnclicked);
}

PropertiesDialog::~PropertiesDialog()
{
    delete ui;
}

void PropertiesDialog::setTableHeader()
{
    ui->tableWidget->setColumnCount(m_tableHeadList.count());
    for(int i = 0; i < m_tableHeadList.count();i++)
    {
        QTableWidgetItem *item = new QTableWidgetItem(m_tableHeadList[i]);
        ui->tableWidget->setHorizontalHeaderItem(i,item);
    }
}

void PropertiesDialog::initTable()
{
    setTableHeader();
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
}

void PropertiesDialog::fillTable(const QString &mode)
{
    QList<Pin> rowValueList;
    if (m_item->getPinActType() == 1)
    {
        rowValueList =  m_item->getUnit().inputPins;
    }
    else if (m_item->getPinActType() == 2)
    {
        rowValueList =  m_item->getUnit().outputPins;
    }
    else
    {
        return;
    }
    ui->tableWidget->setRowCount(rowValueList.count());
    ui->tableWidget->setStyleSheet("QTableWidget { border: 1px solid black; }");
    this->setRowValue(rowValueList);
}

void PropertiesDialog::setRowValue(const QList<Pin> &rowValueList)
{
    for(int i = 0; i < rowValueList.count();i++)
    {
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(rowValueList[i].index));
        ui->tableWidget->setItem(i, 0, idItem);

        QTableWidgetItem *nameItem = new QTableWidgetItem(rowValueList[i].name);
        ui->tableWidget->setItem(i, 1, nameItem);

        QTableWidgetItem *unitItem = new QTableWidgetItem(rowValueList[i].unit);
        ui->tableWidget->setItem(i, 2, unitItem);

        QTableWidgetItem *descItem = new QTableWidgetItem(rowValueList[i].desc);
        ui->tableWidget->setItem(i, 3, descItem);

        QTableWidgetItem *dirItem = new QTableWidgetItem(rowValueList[i].dir);
        ui->tableWidget->setItem(i, 4, dirItem);

        QTableWidgetItem *valueItem = new QTableWidgetItem(rowValueList[i].value);
        ui->tableWidget->setItem(i, 5, valueItem);
    }
    ui->tableWidget->update();
}

void PropertiesDialog::updateButtonStatus()
{
    ui->createButton->setEnabled(currentMode == None);
    ui->delButton->setEnabled(currentMode == None && !ui->tableWidget->selectedItems().isEmpty());
    ui->confirmButton->setEnabled(currentMode == Adding);
    ui->cancelButton->setEnabled(currentMode == Adding);
}

void PropertiesDialog::clearOperationState()
{
    newRow = -1;
    currentMode = None;
    rowToDelete.clear();
}

void PropertiesDialog::onCreateBtnclicked()
{
    clearOperationState();
    currentMode = Adding;
    newRow = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(newRow);
    for (int col = 0; col < ui->tableWidget->columnCount(); ++col) {
        QTableWidgetItem *item = new QTableWidgetItem();
        item->setFlags(item->flags() | Qt::ItemIsEditable);
        ui->tableWidget->setItem(newRow, col, item);
    }
    ui->tableWidget->scrollToBottom();
    ui->tableWidget->editItem(ui->tableWidget->item(newRow,0));
}

void PropertiesDialog::onDelBtnclicked()
{
    clearOperationState();
    QList<QTableWidgetItem *> selectedItem = ui->tableWidget->selectedItems();
    if (selectedItem.isEmpty())
    {
        QMessageBox::warning(this,"Warning","请先选中要删除的行!");
        return;
    }
    else
    {
        // 收集选中的待删除行
        foreach(auto item, selectedItem){
           rowToDelete.insert(item->row());
        }
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this,"确认删除",QString("确认删除选中的%1行吗?").arg(rowToDelete.size()),QMessageBox::Yes | QMessageBox::No);
        if(reply == QMessageBox::Yes)
        {
            QList<int> rows = rowToDelete.toList();
            std::sort(rows.begin(),rows.end(),std::greater<int>());
            foreach (auto row, rows) {
                ui->tableWidget->removeRow(row);
            }
        }
    }
    clearOperationState();

}

void PropertiesDialog::chkCellValid()
{
    bool isValid = true;
    // 检查新增行数据的有效性
    for(int col = 0; col < ui->tableWidget->columnCount();col++)
    {
        auto item = ui->tableWidget->item(newRow,col);
        if(!item || item->text().isEmpty())
        {
            isValid = false;
            break;
        }
    }
    if (!isValid){
        QMessageBox::warning(this, "Warning","请填入有效信息!");
        return;
    }
}

void PropertiesDialog::updatePin()
{
    QList<Pin> pinList;
    pinList.clear();
    QString unitId = m_item->getUnit().id;
    for(int row = 0; row < ui->tableWidget->rowCount();++row)
    {
        struct Pin m_pin;
        m_pin.unitId = unitId;
        m_pin.index = ui->tableWidget->item(row,0)->text().toInt();
        m_pin.name = ui->tableWidget->item(row,1)->text();
        m_pin.unit = ui->tableWidget->item(row,2)->text();
        m_pin.desc = ui->tableWidget->item(row,3)->text();
        m_pin.dir = ui->tableWidget->item(row,4)->text();
        m_pin.value = ui->tableWidget->item(row,5)->text();
        pinList.append(m_pin);
    }
    if (m_item->getPinActType() == 1)
    {
        m_item->getUnit().inputPins.clear();
        m_item->getUnit().setInputPins(pinList);
    }
    else if(m_item->getPinActType() == 2)
    {
        m_item->getUnit().outputPins.clear();
        m_item->getUnit().setOutputPins(pinList);
    }
    else
    {
        return;
    }
}

void PropertiesDialog::updatePinDir(const Unit &unit)
{
    m_item->getPinPointHandleGroup()->updatePinPointHandle(m_item);
    m_item->updatePinPointHandles();
}


void PropertiesDialog::handleChange()
{
    updatePin();
    updatePinDir(m_item->getUnit());
}

void PropertiesDialog::onConfirmBtnclicked()
{
    // 检查新增行是否有效
    if (newRow >= 0 && newRow < ui->tableWidget->rowCount())
    {
        // todo 完善检查单元格所填内容
        // chkCellValid();

        // 锁定新增行的编辑状态
        for (int col = 0; col < ui->tableWidget->columnCount(); ++col) {
            QTableWidgetItem *item = ui->tableWidget->item(newRow, col);
            item->setFlags(item->flags() & Qt::ItemIsEditable);
        }
    }
    clearOperationState();
    handleChange();

    this->close();

}

void PropertiesDialog::onCancelBtnclicked()
{
    if (newRow >= 0 && newRow < ui->tableWidget->rowCount())
        ui->tableWidget->removeRow(newRow);
    clearOperationState();
    this->close();

}
